package org.dromara.book.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import org.dromara.common.idempotent.annotation.RepeatSubmit;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.web.core.BaseController;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.validate.AddGroup;
import org.dromara.common.core.validate.EditGroup;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.excel.utils.ExcelUtil;
import org.dromara.book.domain.vo.SzlyBaseBookTypeVo;
import org.dromara.book.domain.bo.SzlyBaseBookTypeBo;
import org.dromara.book.service.ISzlyBaseBookTypeService;

/**
 * 图书分类
 * 前端访问路由地址为:/book/baseBookType
 *
 * @author LionLi
 * @date 2024-03-15
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/baseBookType")
public class SzlyBaseBookTypeController extends BaseController {

    private final ISzlyBaseBookTypeService szlyBaseBookTypeService;

    /**
     * 查询图书分类列表
     */
    @SaCheckPermission("book:baseBookType:list")
    @GetMapping("/list")
    public R<List<SzlyBaseBookTypeVo>> list(SzlyBaseBookTypeBo bo) {
        if(bo.getParentId()==null){
            bo.setParentId(0L);
        }
        return R.ok(szlyBaseBookTypeService.queryList(bo));
    }

    /**
     * 导出图书分类列表
     */
    @SaCheckPermission("book:baseBookType:export")
    @Log(title = "图书分类", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SzlyBaseBookTypeBo bo, HttpServletResponse response) {
        List<SzlyBaseBookTypeVo> list = szlyBaseBookTypeService.queryList(bo);
        ExcelUtil.exportExcel(list, "图书分类", SzlyBaseBookTypeVo.class, response);
    }

    /**
     * 获取图书分类详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("book:baseBookType:query")
    @GetMapping("/{id}")
    public R<SzlyBaseBookTypeVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(szlyBaseBookTypeService.queryById(id));
    }

    /**
     * 新增图书分类
     */
    @SaCheckPermission("book:baseBookType:add")
    @Log(title = "图书分类", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SzlyBaseBookTypeBo bo) {
        if(bo.getParentId()==null){
            bo.setParentId(0L);
        }
        szlyBaseBookTypeService.insertByBo(bo);
        return toAjax(true);
    }

    /**
     * 修改图书分类
     */
    @SaCheckPermission("book:baseBookType:edit")
    @Log(title = "图书分类", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SzlyBaseBookTypeBo bo) {
        if(bo.getParentId()==null){
            bo.setParentId(0L);
        }
        return toAjax(szlyBaseBookTypeService.updateByBo(bo));
    }

    /**
     * 删除图书分类
     *
     * @param ids 主键串
     */
    @SaCheckPermission("book:baseBookType:remove")
    @Log(title = "图书分类", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(szlyBaseBookTypeService.deleteWithValidByIds(List.of(ids), true));
    }


    /**
     * 爬取全国图书分类数据   后期如果数据变更  及时进行更新
     * @param para1
     * @param index
     * @return
     * @throws IOException
     */
//    @GetMapping("/initData")
    public R<Void> initData(String para1,Integer index) throws IOException {
//        List<Long> collect = szlyBaseBookTypeService.queryList(new SzlyBaseBookTypeBo()).stream().map(i -> i.getId()).collect(Collectors.toList());
//        if(!collect.isEmpty()){
//            szlyBaseBookTypeService.deleteWithValidByIds(collect,false);
//        }
        String s = "http://www.ztflh.com/?c="+para1;
        if(StrUtil.isBlankIfStr(para1)){
            s = "http://www.ztflh.com";
        }
//        getBookType(s,0L);
        Document document = Jsoup.connect(s).get();
        Element list = document.getElementById("list");
//        for (Element li : list.children()) {
            Element span = list.child(index).child(0);
//            Element span = list.child(17).child(0);
            Element a = list.child(index).child(1);
//            Element a = list.child(17).child(1);
            SzlyBaseBookTypeVo szlyBaseBookTypeVo = szlyBaseBookTypeService.queryByCode(span.text());
//        }
//        for (int i = 0; i < list.children().size(); i++) {
//            Element child = list.child(i);
//            Element a = child.child(1);
//            System.out.println(i);
            getBookType(a.attr("href"),szlyBaseBookTypeVo.getId());
//        }
        return R.ok();
    }



//    @Async("async")
    public void getBookType(String url, Long parentId) throws IOException {
        Document document = Jsoup.connect(url).get();
        Element list = document.getElementById("list");
        if (list == null) {
            return;
        }
        List<SzlyBaseBookTypeBo> data = new ArrayList<>();
        ExecutorService executor = Executors.newFixedThreadPool(10); // 创建一个大小为10的线程池
        List<Future<SzlyBaseBookTypeBo>> futures = new ArrayList<>();

        for (Element li : list.children()) {
            Future<SzlyBaseBookTypeBo> future = executor.submit(() -> {
                Element span = li.child(0);
                Element a = li.child(1);
                SzlyBaseBookTypeBo szlyBaseBookTypeBo = new SzlyBaseBookTypeBo();
                szlyBaseBookTypeBo.setCode(span.text());
                szlyBaseBookTypeBo.setName(a.text());
                szlyBaseBookTypeBo.setParentId(parentId);
                return szlyBaseBookTypeService.insertByBo(szlyBaseBookTypeBo);
            });
            futures.add(future);
        }

        for (int i = 0; i < list.children().size(); i++) {
            Future<SzlyBaseBookTypeBo> future = futures.get(i);
            Element child = list.child(i);
            Element a = child.child(1);
            try {
                SzlyBaseBookTypeBo szlyBaseBookTypeBo = future.get();
                getBookType(a.attr("href"), szlyBaseBookTypeBo.getId());
            } catch (InterruptedException | ExecutionException e) {
                // 异常处理
            }
        }

        executor.shutdown();
    }

}
